var express = require('express');
var session = require('express-session');
var app = express();
var path = require("path");
var bodyPharser = require("body-parser");
var mysql   = require('mysql');
var connection = mysql.createConnection({
    host   : 'localhost',
    user   : 'root',
    password : 'lihao2008',
    database : 'test'
});

function isEmptyObject(e) {
    var t;
    for (t in e)
        return !1;
    return !0
}

connection.connect();

app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyPharser.urlencoded({extended:false}));

app.use(session({
    name: 'connect.sid',
    secret: 'keyboard cat',
    cookie: ('name', 'value', { path: '/', httpOnly: true,secure: false, maxAge:  1000*60 }),
    //重新保存：强制会话保存即使是未修改的。默认为true但是得写上
    resave: true,
    //强制“未初始化”的会话保存到存储。
    saveUninitialized: true,
}))

app.get('/signIn.html', function (req, res) {
    res.sendFile( __dirname + "/" + "signIn.html" );
})

app.get('/signUp.html', function (req, res) {
    res.sendFile( __dirname + "/" + "signUp.html" );
})

app.get('/root.html', function (req, res) {
    if(req.session.loginUser) {
        res.sendFile(__dirname + "/" + "root.html");
    }
    else{
        res.redirect('/signIn.html');
    }
})

app.post('/root_cancel',function (req,res) {
    if(req.session.loginUser) {
        var delection = userGetSql = 'DELETE FROM users WHERE id='+'\''+req.body.ID+'\'';
        connection.query(userGetSql,function (err, result) {
            console.log(result);
            res.json({"success":"1"});
        });
    }
    else{
        res.redirect('/signIn.html');
    }
})

app.post('/root_submit',function (req,res) {
    if(req.session.loginUser) {
        var modSql = 'UPDATE users SET pw=? WHERE id = ?';
        var modSqlParams = [req.body.PW,req.body.ID];
        connection.query(modSql,modSqlParams,function (err, result) {
            if(err){
                console.log('[UPDATE ERROR] - ',err.message);
                return;
            }
            res.json({"success":"1"});
        });
    }
    else{
        res.redirect('/signIn.html');
    }
})

app.post('/users_data',function(req,res){
    var selection = userGetSql = 'SELECT * FROM users WHERE id!="root"';
    connection.query(userGetSql,function (err, result) {
        console.log(result);
        res.json(result);
    });
})

app.post('/login_post', function (req,res) {
    var selection = userGetSql = 'SELECT * FROM users WHERE id='+'\''+req.body.ID+'\'';
    connection.query(userGetSql,function (err, result) {
        if(err){
            return;
        }
        if(isEmptyObject(result))
        {
            res.json({"result":"no such id"})
        }
        else{
            if(result[0].pw==req.body.PW){
                if(req.body.ID=="root"){
                    req.session.regenerate(function(err) {
                        if(err){

                        }
                        req.session.loginUser = req.body.ID;
                        res.json({"result":"root"})
                    });
                }
                else{
                    res.json({"result":"login success"});
                }
            }
            else{
                res.json({"result":"wrong password"});
            }
        }

    });
})

app.post('/process_post', function (req, res) {

    // 输出 JSON 格式
    var response = {
        "id":req.body.ID,
        "PW":req.body.PW
    };
    console.log(response);
    var selection = userGetSql = 'SELECT * FROM users WHERE id='+'\''+req.body.ID+'\'';
    connection.query(userGetSql,function (err, result) {
        if(err){
            return;
        }
        if(isEmptyObject(result))
        {
            res.json({"same":"1"});
            var  userAddSql = 'INSERT INTO users(id,pw,email,type) VALUES(?,?,?,?)';
            var  userAddSql_Params = [req.body.ID,req.body.PW,req.body.EMAIL,"1"];
            connection.query(userAddSql,userAddSql_Params,function (err2, result2) {
                if(err){
                    console.log('[INSERT ERROR] - ',err2.message);
                    return;
                }
            });
            return;
        }
        else{
            res.json({"same":"0"});
        }

    });
})

var server = app.listen(8081, function () {

    var host = server.address().address
    var port = server.address().port

    console.log("访问地址为 http://%s:%s", host, port)

})